package chapter1.exercises;

import chapter1.ArrayStack;
import chapter1.Stack;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;

public class exercise139 {
    public static void main(String[] args) {
        Stack<String> ops = new ArrayStack<>();
        Stack<String> vals = new ArrayStack<>();
        while (!StdIn.isEmpty()) {
            String s = StdIn.readString();
            if (s.equals("+")) {
                ops.push(s);
            } else if (s.equals("-")) {
                ops.push(s);
            } else if (s.equals("*")) {
                ops.push(s);
            } else if (s.equals("/")) {
                ops.push(s);
            } else if(s.equals("sqrt")){
                ops.push(s);
            } else if (s.equals(")")) {
                String op = ops.pop();
                if (op.equals("+") || op.equals("-") || op.equals("*") || op.equals("/")) {
                    String v2 = vals.pop();
                    String v1 = vals.pop();
                    String expression = "(" + v1 + op + v2 + "）";
                    vals.push(expression);
                } else if (op.equals("sqrt")) {
                    String v = vals.pop();
                    String expression = op + "(" + v + ")";
                    vals.push(expression);
                }

            } else {
                vals.push(s);
            }
        }
        StdOut.println(vals.pop());
    }
}
